<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      th:replace="admin/layout/base :: html(title='系统概览', content=~{::content}, currentPage='dashboard')">
<head>
    <title>系统概览</title>
</head>
<body>
    <th:block th:fragment="content">
        <!-- 统计卡片 -->
        <div class="row g-4 mb-4">
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="icon bg-primary bg-opacity-10 text-primary">
                        <i class='bx bxs-calendar'></i>
                    </div>
                    <div class="title">今日订单</div>
                    <div class="value" th:text="${todayOrders}">0</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="icon bg-success bg-opacity-10 text-success">
                        <i class='bx bxs-user'></i>
                    </div>
                    <div class="title">活跃用户</div>
                    <div class="value" th:text="${activeUsers}">0</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="icon bg-warning bg-opacity-10 text-warning">
                        <i class='bx bxs-package'></i>
                    </div>
                    <div class="title">回收总量(kg)</div>
                    <div class="value" th:text="${#numbers.formatDecimal(totalWeight, 1, 1)}">0.0</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="icon bg-info bg-opacity-10 text-info">
                        <i class='bx bx-money'></i>
                    </div>
                    <div class="title">系统收入(元)</div>
                    <div class="value" th:text="${#numbers.formatDecimal(totalIncome, 1, 2)}">0.00</div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row">
            <div class="col-md-8 mb-4">
                <div class="chart-card">
                    <div class="card-body">
                        <h5 class="card-title">订单趋势</h5>
                        <div class="chart-container" style="position: relative; height: 300px;">
                            <canvas id="orderTrendChart"></canvas>
                            <div class="chart-loading">加载中...</div>
                            <div class="chart-error" style="display: none;">图表加载失败</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4 mb-4">
                <div class="chart-card">
                    <div class="card-body">
                        <h5 class="card-title">物品分布</h5>
                        <div class="chart-container" style="position: relative; height: 300px;">
                            <canvas id="itemDistributionChart"></canvas>
                            <div class="chart-loading">加载中...</div>
                            <div class="chart-error" style="display: none;">图表加载失败</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 最近订单列表 -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">最近订单</h5>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>订单编号</th>
                                        <th>预约时间</th>
                                        <th>回收地址</th>
                                        <th>联系人</th>
                                        <th>回收员</th>
                                        <th>状态</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr th:each="order : ${recentOrders}">
                                        <td th:text="${order.orderNo}">-</td>
                                        <td th:text="${#temporals.format(order.appointmentTime, 'yyyy-MM-dd HH:mm')}">-</td>
                                        <td th:text="${order.address}">-</td>
                                        <td th:text="${order.userRealName}">-</td>
                                        <td th:text="${order.collectorRealName ?: '-'}">-</td>
                                        <td>
                                            <span th:class="${'badge ' + 
                                                (order.status == 'PENDING' ? 'bg-warning' : 
                                                 order.status == 'PROCESSING' ? 'bg-info' :
                                                 order.status == 'COMPLETED' ? 'bg-success' : 'bg-danger')}"
                                                  th:text="${order.status == 'PENDING' ? '待处理' :
                                                           order.status == 'PROCESSING' ? '处理中' :
                                                           order.status == 'COMPLETED' ? '已完成' : '已取消'}">
                                            </span>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表初始化脚本 -->
        <script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js"></script>
        <script th:inline="javascript">
            console.log('脚本开始执行');
            
            // 获取后端数据
            const orderTrendData = /*[[${orderTrend}]]*/ [];
            const itemDistribution = /*[[${itemDistribution}]]*/ [];
            
            console.log('原始数据:');
            console.log('orderTrendData =', orderTrendData);
            console.log('itemDistribution =', itemDistribution);

            // 等待文档加载完成
            document.addEventListener('DOMContentLoaded', function() {
                console.log('DOM加载完成');
                
                // 获取加载提示元素
                const orderTrendLoading = document.querySelector('#orderTrendChart').parentElement.querySelector('.chart-loading');
                const itemDistLoading = document.querySelector('#itemDistributionChart').parentElement.querySelector('.chart-loading');
                
                // 初始化订单趋势图表
                const orderTrendCtx = document.getElementById('orderTrendChart');
                if (orderTrendCtx) {
                    console.log('找到订单趋势图表元素');
                    try {
                        new Chart(orderTrendCtx, {
                            type: 'line',
                            data: {
                                labels: orderTrendData.map(item => item.month),
                                datasets: [{
                                    label: '订单数量',
                                    data: orderTrendData.map(item => item.count),
                                    fill: true,
                                    borderColor: '#1890ff',
                                    backgroundColor: 'rgba(24, 144, 255, 0.1)',
                                    tension: 0.4,
                                    pointRadius: 4,
                                    pointBackgroundColor: '#1890ff',
                                    borderWidth: 2
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: true,
                                plugins: {
                                    legend: {
                                        display: false
                                    },
                                    tooltip: {
                                        mode: 'index',
                                        intersect: false,
                                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                                        titleColor: '#333',
                                        bodyColor: '#666',
                                        borderColor: '#e1e1e1',
                                        borderWidth: 1,
                                        padding: 10,
                                        displayColors: false
                                    }
                                },
                                scales: {
                                    y: {
                                        beginAtZero: true,
                                        ticks: {
                                            stepSize: 1,
                                            color: '#666'
                                        },
                                        grid: {
                                            color: '#f0f0f0',
                                            drawBorder: false
                                        }
                                    },
                                    x: {
                                        grid: {
                                            display: false
                                        },
                                        ticks: {
                                            color: '#666'
                                        }
                                    }
                                }
                            }
                        });
                        // 隐藏加载提示
                        if (orderTrendLoading) {
                            orderTrendLoading.style.display = 'none';
                        }
                    } catch (error) {
                        console.error('订单趋势图表初始化失败:', error);
                        const errorEl = orderTrendCtx.parentElement.querySelector('.chart-error');
                        if (errorEl) {
                            errorEl.style.display = 'block';
                            errorEl.textContent = '图表加载失败: ' + error.message;
                        }
                        if (orderTrendLoading) {
                            orderTrendLoading.style.display = 'none';
                        }
                    }
                }

                // 初始化物品分布图表
                const itemDistCtx = document.getElementById('itemDistributionChart');
                if (itemDistCtx) {
                    console.log('找到物品分布图表元素');
                    try {
                        // 处理并合并相同类型的数据
                        const mergedData = {};
                        itemDistribution.forEach(item => {
                            let type = item.type;
                            // 标准化类型名称
                            switch(type) {
                                case 'PLASTIC':
                                case '塑料':
                                    type = '塑料';
                                    break;
                                case 'PAPER':
                                case '纸张':
                                case '纸类':
                                    type = '纸类';
                                    break;
                                case 'METAL':
                                case '金属':
                                    type = '金属';
                                    break;
                                case 'GLASS':
                                case '玻璃':
                                    type = '玻璃';
                                    break;
                                case 'FABRIC':
                                case '布料':
                                    type = '布料';
                                    break;
                                case 'ELECTRONICS':
                                case '电子产品':
                                    type = '电子产品';
                                    break;
                                case null:
                                case '':
                                case undefined:
                                    type = '其他';
                                    break;
                                default:
                                    if (!type) type = '其他';
                            }
                            mergedData[type] = (mergedData[type] || 0) + item.count;
                        });

                        // 转换为图表数据格式
                        const labels = Object.keys(mergedData);
                        const data = Object.values(mergedData);

                        new Chart(itemDistCtx, {
                            type: 'doughnut',
                            data: {
                                labels: labels,
                                datasets: [{
                                    data: data,
                                    backgroundColor: [
                                        '#1890ff',  // 塑料
                                        '#2fc25b',  // 纸类
                                        '#facc14',  // 金属
                                        '#223273',  // 玻璃
                                        '#8543e0',  // 布料
                                        '#13c2c2',  // 电子产品
                                        '#999999'   // 其他
                                    ]
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                    legend: {
                                        position: 'right',
                                        labels: {
                                            padding: 20,
                                            font: {
                                                size: 12
                                            }
                                        }
                                    },
                                    tooltip: {
                                        callbacks: {
                                            label: function(context) {
                                                const label = context.label || '';
                                                const value = context.raw || 0;
                                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                                const percentage = ((value / total) * 100).toFixed(1);
                                                return `${label}: ${value} (${percentage}%)`;
                                            }
                                        }
                                    }
                                }
                            }
                        });
                        // 隐藏加载提示
                        if (itemDistLoading) {
                            itemDistLoading.style.display = 'none';
                        }
                    } catch (error) {
                        console.error('物品分布图表初始化失败:', error);
                        const errorEl = itemDistCtx.parentElement.querySelector('.chart-error');
                        if (errorEl) {
                            errorEl.style.display = 'block';
                            errorEl.textContent = '图表加载失败: ' + error.message;
                        }
                        if (itemDistLoading) {
                            itemDistLoading.style.display = 'none';
                        }
                    }
                }
            });
        </script>

        <style>
            .chart-card {
                background: #fff;
                border-radius: 8px;
                box-shadow: 0 0 15px rgba(0,0,0,0.05);
            }
            
            .chart-card .card-body {
                padding: 20px;
            }
            
            .chart-card .card-title {
                margin-bottom: 20px;
                color: #2c3e50;
                font-weight: 600;
            }
            
            .chart-container {
                position: relative;
                height: 300px;
                width: 100%;
            }
            
            .chart-loading, .chart-error {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                text-align: center;
                color: #666;
            }
            
            .chart-error {
                color: #dc3545;
            }
        </style>
    </th:block>
</body>
</html> 